<template>
	<view class="details">
		<view class="com_add_btn" @click="onAdd">
			添加+
		</view>
		<view v-if="regime.classifyId == 9" style="width: 90%; margin: 0 auto; margin-top: 10rpx;">
			<up-subsection @change="onOps" :list="listOps" :current="current1"></up-subsection>
		</view>

		<view class="dateCalendar" v-if="current1 == 0">
			<uni-calendar ref="calendar1" :selected="selected" :insert="true" :lunar="true" :start-date="startDate" :end-date="endDate" @change="onSelectData" />
		</view>

		<view class="dateCalendar" v-if="current1 == 1">
			<uni-calendar ref="calendar2" :selected="selected" :insert="true" :lunar="true" :start-date="startDate" :end-date="endDate" @change="onSelectData" />
		</view>

		<view class="dataOps-num" v-if="regime.classifyId != 9">
			<view>
				<text>查询到：{{size}}条记录</text>
			</view>

			<view style="display: flex; align-items: center;">
				<view class="display_flex">
					<text v-if="isSelection" @click="isSelection =!isSelection " style="color: #303133; margin-right: 20rpx;">取消</text>

					<text v-if="isSelection" @click="onSelector" style="color: #F56C6C; margin-right: 20rpx;">全选</text>

					<text v-if="!isSelection" @click="isSelection =!isSelection" style="margin-right: 20rpx; color: #303133;">选择</text>
					<text v-if="isSelection" @click="doc_del" style="margin-right: 20rpx; color: #303133;">删除</text>

					<button v-if="isSelection" open-type="share" class="custom-share-btn">分享</button>
				</view>
			</view>
		</view>
		<view v-else>
			<view v-if="current1 == 0">
				<view class="dataOps-num">
					<view>
						<text>查询到：{{size}}条记录</text>
					</view>

					<view style="display: flex; align-items: center;">
						<view class="display_flex">
							<text v-if="isSelection" @click="isSelection =!isSelection " style="color: #303133; margin-right: 20rpx;">取消</text>

							<text v-if="isSelection" @click="onSelector" style="color: #F56C6C; margin-right: 20rpx;">全选</text>

							<text v-if="!isSelection" @click="isSelection =!isSelection" style="margin-right: 20rpx; color: #303133;">选择</text>

							<button v-if="isSelection" open-type="share" class="custom-share-btn">分享</button>
						</view>
					</view>
				</view>
			</view>
			<view v-if="current1 == 1">
				<view class="dataOps-num">
					<view>
						<text>查询到：{{hotWorkCertificateLogJson.length}}条记录</text>
					</view>

					<view style="display: flex; align-items: center;">
						<view class="display_flex">
							<text v-if="isSelectionOne" @click="delSta" style="color: #303133; margin-right: 20rpx;">取消</text>

							<text v-if="isSelectionOne" @click="onSelector('one')" style="color: #F56C6C; margin-right: 20rpx;">全选</text>

							<text v-if="!isSelectionOne" @click="isSelectionOne =!isSelectionOne" style="margin-right: 20rpx; color: #303133;">选择</text>

							<button v-if="isSelectionOne" open-type="share" class="custom-share-btn">分享1</button>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view v-if="current1 == 1">
			<fui-list v-if="!isSelection">
				<fui-list-cell :key="index" size="12" footerSize="12" @longpress="onShowOps(itme)" v-for="(itme,index) in hotWorkCertificateLogJson" class="border_bottom_normal" :arrow="!isSelectionOne">
					<view style="width: 100%;">
						<view class="display_flex space_between margin_bottom_normal" style="width: 100%;">
							<text>{{itme.title}}</text>
							<view class="display_flex">
								<text style="margin-right: 40rpx;"> {{ itme.creationTime}}</text>
								<view class="margin_right_normal">
									<fui-checkbox v-if="isSelectionOne" @change="onChecked(itme,'one')" v-model="itme.isChecked" :checked="itme.isChecked" :value="index"></fui-checkbox>
								</view>
							</view>
						</view>
						<text>{{itme?.content}}</text>
					</view>
				</fui-list-cell>
			</fui-list>
			<!-- <fui-collapse-item v-for="(item,index) in hotWorkCertificateLogJson" :key="index"
				:title="item.title ">
				<view class="fui-item__box">
					<text>{{item.title}}</text>
				</view>
				<template v-slot:content>
					<view style="width: 97%; margin: 0 auto;">
						<up-text :text="item.content"></up-text>
					</view>
					<view class="">
						<fui-input color="#606266" labelColor="#606266" textAlign ="right" readonly :value="item.creationTime" label="记录时间:" borderTop></fui-input>
					</view>
				</template>
			</fui-collapse-item> -->

		</view>
		<view v-if="current1 == 0">
			<view class="u-page__item" v-if="size > 0">
				<fui-list v-if="!isSelection">
					<fui-list-cell :key="index" size="12" footerSize="12" @longpress="onShowOps(itme)" v-for="(itme,index) in newOpsList" @click="toViewDoc(itme)" arrow>
						<view style="display: flex;align-items: center;">
							<text>记录用户：{{itme.name}}</text>
							<view class="fui-text__explain">
								<text style="margin-right: 80rpx;"> {{ itme.recordTime}}</text>
							</view>

						</view>
					</fui-list-cell>
				</fui-list>

				<fui-list v-if="isSelection">
					<fui-list-cell size="12" :key="index" footerSize="12" v-for="(itme,index) in newOpsList" @click="onChecked(itme)">
						<view style="display: flex;align-items: center;">
							<text>记录用户：{{itme.name}}</text>

							<view class="fui-text__explain">
								<text style="margin-right: 20rpx;"> {{ itme.recordTime}}</text>

								<fui-checkbox style="margin-right: 20rpx;" @change="onChecked(itme)" v-model="itme.isChecked" :checked="itme.isChecked" :value="index"></fui-checkbox>
							</view>
						</view>
					</fui-list-cell>
				</fui-list>
			</view>
		</view>

		<view>
			<u-modal :show="moda.show" @cancel="onModalClose" @confirm="onModal" :title="moda.title" :showCancelButton="true">
				<view class="slot-content">
					<view>
						<u--input readonly placeholder="请输入操作员姓名" v-model="ops.name" border="bottom" clearable></u--input>
					</view>
					<view style="margin-top: 20rpx;" v-if="!isJournal">
						<u-button type="primary" @click="addJournal" text="添加日志"></u-button>
					</view>
					<view style="margin-top: 20rpx;" v-if="isJournal">
						<u-button type="primary" text="已添加日志"></u-button>
					</view>
				</view>

			</u-modal>
		</view>

		<view>
			<fui-actionsheet maskClosable @cancel="showOps =!showOps" :show="showOps" @click="onDels" :itemList="itemList"></fui-actionsheet>
		</view>
		<view>
			<up-action-sheet :round="10" @close="show1 =!show1" @select="onActionSelect" :actions="list1" :closeOnClickOverlay="true" :closeOnClickAction="true" title="查看" :show="show1"></up-action-sheet>
		</view>
	</view>
</template>

<script>
	// #ifdef APP-PLUS
	const wpsTool = uni.requireNativePlugin("CL-WPSTool");
	const FileShare = uni.requireNativePlugin('life-FileShare'); //分享插件
	const open = uni.requireNativePlugin("Html5App-openFile");
	// #endif
	// #ifdef MP-WEIXIN || H5
	const wpsTool = ""
	const FileShare = ""
	const open = ""
	// #endif

	import moment from "moment"
	import {
		BASE_IP
	} from '@/common/http/url.js'

	import tools from "@/tools/tools.js"
	import {
		data
	} from "uview-ui/libs/mixin/mixin";
	export default {
		name: "details",
		data() {
			return {
				isSelectionOne: false,
				current1: 0,
				listOps: ['动用明火记录', '动火证书报警记录'],
				moda: {
					show: false,
					title: "",
					content: ""
				},
				ops: {
					name: "",
					journal: "",
					signature: ""
				},
				regime: "",
				opsList: [],
				isJournal: false,
				isSignature: false,
				title: "记录时间：",
				user: "",
				dataList: ['今天', '三天', '一周', '一个月'],
				current: 0,
				newOpsList: [],
				startDate: "",
				endDate: "",
				selected: [],
				relativepath: "",
				fills: [],
				workRecordTime: 0,
				isToday: true,
				showOps: false,
				itemList: [{
					text: "分享2",
					color: "#409EFF"
				}, {
					text: '删除',
					color: '#FF2B2B'
				}],
				itmes: "",
				isSelection: false,
				pralldata: "",
				day: "",
				size: 0,
				list1: [{
					id: 0,
					name: "查看文档记录"
				}, {
					id: 1,
					name: "查看巡检图片"
				}],
				show1: false,
				tempItem: "",
				hotWorkCertificateLogJson: [],
				hotWorkCertificateLogDate: [],
				recordList: []

			}
		},
		onShareAppMessage() {
			let newOpsList = this.newOpsList
			let itmepdf = newOpsList[0]
			let name = this.regime.classifyName + "-" + itmepdf.recordTime + ".pdf"
			let nameStr = name.replace(/\s/g, "-")
			console.log(nameStr)
			let arrList = new Array()
			newOpsList.forEach((itme) => {
				if (itme.isChecked) {
					arrList.push(itme)
				}
			})
			// console.log(arrList)
			// if (arrList.length < 1) {
			// 	uni.showToast({
			// 		title: "请选择文件",
			// 		icon: "error"
			// 	})
			// 	return
			// }
			return {
				title: nameStr,
				path: '/pagesWork/webview/webview?arrList=' + JSON.stringify(arrList),
				imageUrl: 'https://mp-bfea0f33-0deb-44c8-86f2-196dd6ca37a5.cdn.bspapp.com/test/head.jpg',
				success(res) {},
				fail(err) {}
			}
		},
		methods: {
			onAdd() {
				let regime = this.regime
				let user = uni.getStorageSync("user");
				if (user.nickName == "" || user.nickName == null || user.nickName == undefined) {
					uni.showModal({
						title: "提示",
						content: "姓名为空，请前往“用户中心-设置-编辑资料-用户名”设置姓名",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: "/pagesMine/settting/editingData/editingData"
								})
								return
							}
						}
					})
					return
				}
				let pralldata = this.pralldata
				if (pralldata.operatingTimeStart == "" || pralldata.operatingTimeStart == null || pralldata
					.operatingTimeStart == undefined) {
					uni.showModal({
						title: "提示",
						content: "请前往-预设功能-完善该单位经营开始时间",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: "/pagesWork/preinstall/preinstall"
								})
								return
							}
						}
					})
					return
				}

				if (pralldata.operatingTimeEnd == "" || pralldata.operatingTimeEnd == null || pralldata.operatingTimeEnd ==
					undefined) {
					uni.showModal({
						title: "提示",
						content: "请前往-预设功能-完善该单位经营结束时间",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: "/pagesWork/preinstall/preinstall"
								})
								return
							}
						}
					})
					return
				}

				if (this.regime.classifyId == 1) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/firePatrol/firePatrol?regime=" + JSON.stringify(regime)
					})
					return
				} else if (this.regime.classifyId == 2) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/fireExtinguishing/fireExtinguishing?regime=" + JSON.stringify(
							regime)
					})
					return
				} else if (this.regime.classifyId == 3) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/fireControlRoom/fireControlRoom?regime=" + JSON.stringify(
							regime)
					})
					return
				} else if (this.regime.classifyId == 4) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/fireHydrantCheckList/fireHydrantCheckList?regime=" + JSON
							.stringify(
								regime)
					})
					return
				} else if (this.regime.classifyId == 5) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/buildingFireProtection/buildingFireProtection?regime=" + JSON
							.stringify(
								regime)
					})
					return
				} else if (this.regime.classifyId == 6) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/fullTime/fullTime?regime=" + JSON.stringify(regime)
					})
					return
				} else if (this.regime.classifyId == 7) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/fireExtinguishingMeter/fireExtinguishingMeter?regime=" + JSON
							.stringify(
								regime)
					})
					return
				} else if (this.regime.classifyId == 8) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/annualFireProtection/annualFireProtection?regime=" + JSON
							.stringify(
								regime)
					})
					return
				} else if (this.regime.classifyId == 9) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/useOpenFire/useOpenFire?regime=" + JSON.stringify(regime)
					})
					return
				} else if (this.regime.classifyId == 10) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/fileMonitoringControl/fileMonitoringControl?regime=" + JSON
							.stringify(
								regime)
					})
					return
				} else if (this.regime.classifyId == 11) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/fireSafetyPublicityTrainingRecordForm/fireSafetyPublicityTrainingRecordForm?regime=" +
							JSON.stringify(regime)
					})
					return
				} else if (this.regime.classifyId == 12) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/fireControlRectificationReform/fireControlRectificationReform?regime=" +
							JSON.stringify(regime)
					})
					return
				} else if (this.regime.classifyId == 13) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/fireFightingFacilities/fireFightingFacilities?regime=" + JSON
							.stringify(
								regime)
					})
					return
				} else if (this.regime.classifyId == 14) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/fireSafety/fireSafety?regime=" + JSON.stringify(regime)
					})
					return
				} else if (this.regime.classifyId == 15) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/fireFightingPeriod/fireFightingPeriod?regime=" + JSON.stringify(
							regime)
					})
					return
				} else if (this.regime.classifyId == 16) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/fireProtectionTest/fireProtectionTest?regime=" + JSON.stringify(
							regime)
					})
					return
				} else if (this.regime.classifyId == 17) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/fireControlAcceptance/fireControlAcceptance?regime=" + JSON
							.stringify(
								regime)
					})
					return
				} else if (this.regime.classifyId == 18) {
					uni.navigateTo({
						url: "/pagesWork/recordTab/fireFireProtectionMaintenanceTransferlist/fireFireProtectionMaintenanceTransferlist?regime=" +
							JSON.stringify(
								regime)
					})
					return
				}
				this.ops.name = user.nickName
				this.moda.show = true

				// console.log(this.regime)

			},
			onOps(res) {
				console.log(res)
				this.current1 = res
				if (res == 0) {
					this.selected = []
					this.selected = this.recordList
				}
				if (res == 1) {
					this.selected = []
					this.selected = this.hotWorkCertificateLogDate
				}
				console.log(this.current1)
			},
			onActionSelect(res) {
				console.log(res)
				if (res.id == 0) {
					this.toViewDocSon(this.tempItem)
				}
				let item = this.tempItem
				if (res.id == 1) {
					if (item.recordLogImg != "" && item.recordLogImg != undefined) {
						let img = JSON.parse(item.recordLogImg)
						let urls = []
						img.forEach((it, index) => {
							console.log(it)
							let url = BASE_IP + it
							console.log("url：", url)
							urls.push(url)
						})
						uni.previewImage({
							current: 0,
							urls: urls
						});
						console.log(img)
						console.log(this.regime)
						return
					} else {
						uni.showToast({
							title: "无巡检图片",
							icon: "error"
						})
					}
				}
			},
			onShares() {
				let newOpsList = this.newOpsList
				let itmepdf = newOpsList[0]
				let name = this.regime.classifyName + "-" + itmepdf.recordTime + ".pdf"
				let nameStr = name.replace(/\s/g, "-")
				console.log(nameStr)
				let arrList = new Array()
				newOpsList.forEach((itme) => {
					if (itme.isChecked) {
						arrList.push(itme)
					}
				})
				// console.log(arrList)
				if (arrList.length < 1) {
					uni.showToast({
						title: "请选择文件",
						icon: "error"
					})
					return
				}

				let user = uni.getStorageSync("user")
				let url = BASE_IP + "pc/record/merge/pdfs"
				uni.request({
					url: url,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						"Authorization": user.token
					},
					method: "POST",
					data: {
						recordList: JSON.stringify(arrList),
						test: "test"
					},
					success: (res) => {
						if (res.statusCode == 200) {
							let u = BASE_IP + res.data
							console.log(u)
							this.sharePdf(u, nameStr)
						}
						if (res.statusCode == 404) {
							uni.showToast({
								title: "请求失败",
								icon: "error"
							})
						}
						if (res.statusCode == 500) {
							uni.showToast({
								title: "请求失败",
								icon: "error"
							})
						}
					},
					fail: () => {
						uni.showToast({
							title: "请求失败",
							icon: "error"
						})
						return
					}
				})
			},
			delSta() {
				let temp = this.hotWorkCertificateLogJson
				temp.forEach((r) => {
					r.isChecked = false
				})
				this.hotWorkCertificateLogJson = temp
				this.isSelectionOne = false
			},
			onSelector(item) {
				if (item == 'one') {
					let temp = this.hotWorkCertificateLogJson
					temp.forEach((r) => {
						r.isChecked = true
					})
					this.hotWorkCertificateLogJson = temp
				} else {
					let temp = this.newOpsList
					temp.forEach((r) => {
						r.isChecked = true
					})
					this.newOpsList = temp
				}
			},
			// ... existing code ...
			// ... existing code ...
			doc_del() {
				// 获取选中的记录
				let selectedItems = this.newOpsList.filter(item => item.isChecked);
				if (selectedItems.length === 0) {
					uni.showToast({
						title: "请选择要删除的记录",
						icon: "error"
					});
					return;
				}

				uni.showModal({
					title: "提示",
					content: `确定要删除选中的${selectedItems.length}条记录吗？`,
					success: (res) => {
						if (res.confirm) {
							let user = uni.getStorageSync("user");
							// 构建要删除的记录ID数组
							let recordIds = selectedItems.map(item => item.recordId);

							// 调用批量删除接口
							uni.request({
								url: BASE_IP + "pc/record/remove/logic",
								method: "post",
								header: {
									"Authorization": user.token,
									"Content-Type": "application/json"
								},
								data: recordIds,
								success: (res) => {
									if (res.statusCode === 200) {
										uni.showToast({
											title: "删除成功",
											icon: "success"
										});
										// 刷新数据
										this.getCollapseDatas();
										// 退出选择模式
										this.isSelection = false;
									} else {
										uni.showToast({
											title: "删除失败",
											icon: "error"
										});
									}
								},
								fail: () => {
									uni.showToast({
										title: "删除失败",
										icon: "error"
									});
								}
							});
						}
					}
				});
			},
			// ... existing code ...
			// ... existing code ...
			onChecked(res, sta) {
				if (sta == 'one') {
					console.log(res)
					let temp = this.hotWorkCertificateLogJson
					temp.forEach((r) => {
						if (r.id == res.id) {
							r.isChecked = !r.isChecked
						}
					})
					this.hotWorkCertificateLogJson = temp
				} else {
					// console.log(res)
					let temp = this.newOpsList

					temp.forEach((r) => {
						if (r.recordId == res.recordId) {
							r.isChecked = !r.isChecked
						}
					})
					this.newOpsList = temp
				}
			},
			onDels(res) {
				// console.log(res)
				if (res.index == 0) {
					this.onShare(this.itmes)
				} else if (res.index == 1) {
					this.onDel(this.itmes)
				}
				this.showOps = !this.showOps
			},
			onShowOps(itme) {
				this.itmes = itme
				this.showOps = true

			},
			onDel(itme) {
				// console.log(itme)
				let user = uni.getStorageSync("user")
				let url = BASE_IP + "pc/record/record/" + itme.recordId
				uni.request({
					header: {
						"Authorization": user.token,
					},
					url: url,
					method: "DELETE",
					success: (res) => {
						console.log(res)
						if (res.statusCode == 200) {
							setTimeout(() => {
								this.getCollapseDatas()
							}, 500)
							// setTimeout(() => {
							// 	this.getCollapseDatas()
							// }, 800)
						} else if (res.statusCode == 404) {
							uni.showToast({
								title: "删除",
								icon: "error"
							})
							return
						}
					},
					fail: () => {
						uni.showToast({
							title: "删除",
							icon: "error"
						})
					}
				})
			},
			wordToPDF(link) {
				let result = ""
				uni.showLoading({
					title: "正在加载"
				})
				let user = uni.getStorageSync("user")
				let url = BASE_IP + "pc/iotFireAlarmRecord/wordToPdf?url=" + link
				let _this = this
				uni.request({
					header: {
						"Authorization": user.token,
					},
					url: url,
					method: "POST",
					success: (res) => {
						uni.hideLoading();
						this.toWord(res.data.path)
					},
					fail: (res) => {
						uni.hideLoading();
						uni.showToast({
							icon: "error",
							title: "服务器出现问题"
						})
					}
				})
				return result
			},
			toWord(link) {
				// if (true) {
				// 判断手机类型是 Android 还是 ios
				let url = BASE_IP + link
				console.log(url)
				uni.navigateTo({
					url: "/pagesWork/webview/webview?src=" + url
				})
				return;
				if (uni.getSystemInfoSync().platform === 'android') {
					let is = open.isLoadTbs();
					if (!is) {
						this.installLocalTbs()
						return
					}
					uni.downloadFile({
						url: url,
						success: (res) => {
							uni.hideLoading()
							if (res.statusCode === 200) {
								const {
									tempFilePath
								} = res;
								let filePath = plus.io.convertLocalFileSystemURL(tempFilePath);
								open.openFile({
									filename: filePath,
									isShowBackIcon: true
								}, ret => {
									console.log(ret)
								});
							}
						},
						fail: (e) => {
							uni.hideLoading()
							// console.log(e);
							uni.showModal({
								content: JSON.stringify(e) + "失败"
							})
						}
					})
				} else {
					uni.downloadFile({
						url: url,
						success: (res) => {
							uni.hideLoading()
							if (res.statusCode === 200) {
								const {
									tempFilePath
								} = res;
								let filePath = plus.io.convertLocalFileSystemURL(tempFilePath);
								open.openFile({
									filename: filePath,
									isShowBackIcon: true
								}, ret => {});
							}
						},
						fail: (e) => {
							uni.hideLoading()
							// console.log(e);
							uni.showModal({
								content: JSON.stringify(e) + "失败"
							})
						}
					})
				}
			},
			onShare(itme) {
				uni.showLoading({
					title: "正在加载",
					mask: true
				})
				var docxPattern = /\.docx$/i; // 匹配以 .docx 结尾的正则表达式
				var pdfPattern = /\.pdf$/i; // 匹配以 .pdf 结尾的正则表达式
				let user = uni.getStorageSync("user")
				let url = BASE_IP + "pc/iotFireAlarmRecord/wordToPdf?url=" + itme.recordLogUpload
				let name = this.regime.classifyName + "-" + itme.recordTime + ".pdf"
				let nameStr = name.replace(/\s/g, "-")
				if (docxPattern.test(itme.recordLogUpload)) {
					let _this = this
					uni.request({
						header: {
							"Authorization": user.token,
						},
						url: url,
						method: "POST",
						success: (res) => {
							uni.hideLoading();
							this.sharePdf(BASE_IP + res.data.path, nameStr)
						},
						fail: (res) => {
							uni.hideLoading();
							uni.showToast({
								icon: "error",
								title: "服务器出现问题"
							})
						}
					})
				} else if (pdfPattern.test(itme.recordLogUpload)) {
					uni.hideLoading();
					this.sharePdf(BASE_IP + itme.recordLogUpload, nameStr)
				} else {

				}




			},
			sharePdf(url, name) {
				// 下面使用这个下载方式，亲测，如果用uniapp自身的ios中文乱码，下面可以重命名不会乱码，分享就是FileShare调用
				var dtask = plus.downloader.createDownload(url, {
					filename: "_doc/pdf/" + name
				}, function(d, status) {
					// 下载完成
					if (status == 200) {
						FileShare.render({
							type: "SYSTEM", //QQ为QQ，微信为WX，系统默认是SYSTEM，不填写默认SYSTEM
							filePath: plus.io.convertLocalFileSystemURL(d.filename),
						}, result => {

						});
					} else {
						// console.log("Download failed: " + status);
					}
				});
				dtask.start();
			},
			downLoadFile(url) { //ios
				// testModule.downLoadFile({
				// 	'url': url,
				// 	'header': {}
				// }, (ret) => {
				// 	console.log(ret)
				// })
			},
			onModal() {
				if (!this.isJournal) {
					uni.showToast({
						title: "请添加日志",
						icon: "error"
					})
					return
				}

				if (this.relativepath == "") {
					uni.showToast({
						title: "请保存日志",
						icon: "error"
					})
					return
				}

				this.upload(this.relativepath)

				this.moda.show = false
				let time = setTimeout((res => {
					this.getCollapseDatas()
				}), 500)

				let time1 = setTimeout((res => {
					this.getCollapseDatas()
				}), 800)
				this.isJournal = !this.isJournal
			},
			onModalClose() {

				this.moda.show = false
			},
			addJournal() {
				if (this.ops.name == "") {
					uni.showToast({
						title: "请输入姓名",
						icon: "error"
					})
					return
				}
				if (this.regime.upload == "") {
					uni.showToast({
						title: "请上传模版",
						icon: "error"
					})
					return
				}
				let url = BASE_IP + this.regime.upload
				uni.downloadFile({
					url: url,
					success: (res) => {
						let temp = plus.io.convertLocalFileSystemURL(res.tempFilePath)
						this.editorDocInfo(temp)
					},
					fail: (res) => {
						uni.showToast({
							icon: 'none',
							mask: true,
							title: '失败请重新下载',
						});
					}
				})
			},
			editorDocInfo(url) {
				//filePath 为绝对路径;
				let name = this.ops.name
				let options = {
					filePath: url, //文件路径 必填
					userName: name, //必填，用于记录编辑信息
					isEnterReviseMode: true //是否进入修订模式,默认true(该模式用于记录文档修改日志)
				};

				wpsTool.wpsEditorFile(options, result => {
					// console.log(result);
					const {
						code,
						msg
					} = result;
					if (code == 1) {
						this.isJournal = true
						//成功;
						let newPath = result.path; //该路径为绝对路径;
						//将绝对路径转相对路径;用于上传到服务器的;
						let relativepath = plus.io.convertAbsoluteFileSystem(newPath); //为平台的相对路径，可以用于上传到服务器;
						this.relativepath = relativepath
					} else {
						//失败情况;

					}
					//如果想将文件进行上传;需将绝对路径转成相对路径;
				})
			},
			upload(filePath) {
				let user = uni.getStorageSync("user")
				let name = this.ops.name
				let url = BASE_IP + "pc/record/record"
				let classifyId = this.regime.classifyId
				uni.uploadFile({
					header: {
						"Authorization": user.token,
					},
					url: url,
					name: "file",
					filePath: filePath,
					formData: {
						unitId: user.unitId,
						name: name,
						classifyId: classifyId,
					},
					success: (res) => {
						if (res.statusCode == 200) {
							uni.showToast({
								title: "上传成功",
								icon: "success"
							})
						}
						if (res.statusCode == 500) {
							uni.showToast({
								title: "上传失败",
								icon: "error"
							})
						}
					},
					fail: () => {
						uni.showToast({
							title: "上传失败",
							icon: "error"
						})
					}
				})
			},
			onSignaturesSon() {
				let user = uni.getStorageSync("user")
				if (user.signature == "" || user.signature == undefined || user.signature == null) {
					uni.showModal({
						title: "提示",
						content: "用户未上传签名请前往“预设功能-添加操作员-输入账号-添加签名”，如果已添加操作员上传签名即可",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								return
							}
						}
					})
					return
				}
				let url = BASE_IP + user.signature
				uni.downloadFile({ //下载
					url: url, //图片下载地址
					success: res => {
						if (res.statusCode === 200) {
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: (r) => {
									// console.log(r)
									// this.upLoadSeal(r.savedFilePath, item.path)
									this.upload(r.savedFilePath)
								}
							})
						}
					}
				});
			},
			onSignatures() {
				if (this.ops.name == "") {
					uni.showToast({
						title: "请输入姓名",
						icon: "error"
					})
					return
				}

				// signatures.gotoSignPage({
				// 	themeColor: '#55aaff'
				// }, res => {
				// 	// this.signaturesPath = res[0]
				// 	let relativepath = plus.io.convertAbsoluteFileSystem(res[0]); //为平台的相对路径，可以用于上传到服务器;
				// 	// console.log("路径:", relativepath)
				// 	this.upload(relativepath)
				// })

				let user = uni.getStorageSync("user")
				if (user.signature == "" || user.signature == undefined || user.signature == null) {
					uni.showModal({
						title: "提示",
						content: "用户未上传签名请前往“预设功能-添加操作员-输入账号-添加签名”，如果已添加操作员上传签名即可",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								return
							}
						}
					})
					return
				}
				let url = BASE_IP + user.signature
				uni.downloadFile({ //下载
					url: url, //图片下载地址
					success: res => {
						if (res.statusCode === 200) {
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: (r) => {
									// console.log(r)
									// this.upLoadSeal(r.savedFilePath, item.path)
									this.upload(r.savedFilePath)
								}
							})
						}
					}
				});

				this.isSignature = true
			},
			getCollapseDatas() {
				let user = uni.getStorageSync("user")
				console.log('uu', user, user.unitId);
				let classifyId = this.regime.classifyId
				let url = BASE_IP + "pc/record/query/new/" + user.unitId + "/" + classifyId + "/" + this.day
				uni.request({
					header: {
						"Authorization": user.token,
					},
					url: url,
					success: (res) => {
						console.log("結果：", res)
						if (res.statusCode == 200) {
							let recordList = JSON.parse(res.data.recordList)
							let dayList = JSON.parse(res.data.dayList)
							console.log(recordList)
							console.log(dayList)
							let temp = []
							for (let index in dayList) {
								let red = JSON.parse(dayList[index])
								temp.push(red)
							}
							this.recordList = recordList
							this.selected = recordList

							temp.sort((a, b) => {
								let dateA = new Date(a.recordTime);
								let dateB = new Date(b.recordTime);
								return dateB - dateA; // 降序排列
							});

							this.newOpsList = temp

							this.size = res.data.size

							if (this.regime.classifyId == 9) {
								console.log("1234567", res.data.hotWorkCertificateLogJson)
								console.log("1234567", res.data.hotWorkCertificateLogDate)
								if (res.data.hotWorkCertificateLogJson == undefined || res.data
									.hotWorkCertificateLogJson == null || res.data.hotWorkCertificateLogJson ==
									"") {
									return
								}
								if (res.data.hotWorkCertificateLogDate == undefined || res.data
									.hotWorkCertificateLogDate == null || res.data.hotWorkCertificateLogDate ==
									"") {
									return
								}
								let hotWorkCertificateLogJson = JSON.parse(res.data.hotWorkCertificateLogJson)
								let hotWorkCertificateLogDate = JSON.parse(res.data.hotWorkCertificateLogDate)
								let hotWorkCertificateLogJsonTemp = []
								let hotWorkCertificateLogDateTemp = []
								for (let index in hotWorkCertificateLogJson) {
									let data = hotWorkCertificateLogJson[index]
									console.log("========>", data)
									hotWorkCertificateLogJsonTemp.push(JSON.parse(data))
								}
								// for(let index in hotWorkCertificateLogDate){
								// 	hotWorkCertificateLogDateTemp.push(JSON.parse(hotWorkCertificateLogDate[index]))
								// }
								console.log(111111, hotWorkCertificateLogJsonTemp)

								console.log(hotWorkCertificateLogDate)

								hotWorkCertificateLogJsonTemp.sort((a, b) => {
									let dateA = new Date(a.creationTime);
									let dateB = new Date(b.creationTime);
									return dateB - dateA; // 降序排列
								});
								this.hotWorkCertificateLogJson = hotWorkCertificateLogJsonTemp
								this.hotWorkCertificateLogDate = hotWorkCertificateLogDateTemp
							}

							// console.log(recordList)
							// console.log("temp：", temp)

							// uni.removeStorageSync("opsList")
							// uni.setStorageSync("opsList", res.data)
							// this.opsList = res.data
							// console.log(res)
							// this.setDataOps(this.endDate,res.data)
							// this.dataMarking(res.data)
						}
						if (res.statusCode == 500) {

						}
					}
				})
				uni.stopPullDownRefresh()
				// setTimeout((res=>{
				// 	let opsList = uni.getStorageSync("opsList")
				// console.log(opsList)

				// }),500)
			},
			toViewImg(item) {
				let user = uni.getStorageSync("user")
				if (user.signature == "" || user.signature == undefined || user.signature == null) {
					uni.showModal({
						title: "提示",
						content: "用户未上传签名请前往“预设功能-添加操作员-输入账号-添加签名”，如果已添加操作员上传签名即可",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								return
							}
						}
					})
					return
				}
				let docPath = item.recordLogUpload
				let url = BASE_IP + user.signature
				// console.log(url)
				let _this = this
				uni.downloadFile({ //下载
					url: url, //图片下载地址
					success: res => {
						if (res.statusCode === 200) {
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: (r) => {
									// console.log(r)
									_this.upSignature(r.savedFilePath, docPath, item)
								}
							})
						}
					}
				});
			},
			toViewDoc(item) {
				console.log(item)
				console.log(this.regime.classifyId)
				if (this.regime.classifyId == 1) {
					console.log("测试测试：", item.recordLogImg)
					this.show1 = !this.show1
					this.tempItem = item

				} else {
					console.log("动火记录")
					this.toViewDocSon(item)
				}
			},
			toViewDocSon(item) {
				console.log(1111, item)
				var docxPattern = /\.docx$/i; // 匹配以 .docx 结尾的正则表达式
				var pdfPattern = /\.pdf$/i; // 匹配以 .pdf 结尾的正则表达式

				if (docxPattern.test(item.recordLogUpload)) {
					console.log("pdf")
					this.wordToPDF(item.recordLogUpload)
				} else if (pdfPattern.test(item.recordLogUpload)) {
					console.log("word")
					this.toWord(item.recordLogUpload)
				}
			},
			installLocalTbs() {
				let url = BASE_IP + "static/tbs/arm64-v8a.tbs"
				uni.downloadFile({
					url: url,
					success: (res) => {
						if (res.statusCode == 200) {
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: (r) => {
									let filepath = plus.io.convertLocalFileSystemURL(r
										.savedFilePath);
									open.installLocalTbs({
										tbsFilePath: filepath,
										isdelete: false //安装好是否要删除该文件
									}, function(e) {
										console.log("安装 tbs 内核" + JSON.stringify(e));
										if (e.code == 0) {
											uni.showToast({
												title: "安装TBS 请重新打开",
												icon: "none"
											});
										} else {
											uni.showToast({
												title: e.msg,
												icon: "none"
											});
										}
									});
								}
							})
						}
					}
				})
				//安装 tbs 离线内核, 在适当的时候安装tbs 浏览内核,安装一次即可
			},
			openDocInfo(filePath, isEditor, itme) {
				if (!isEditor) {
					wpsTool.wpsOpenFile(filePath, result => {
						// console.log(result + "aaa");
					})
				} else {
					// let user = uni.getStorageSync("user")
					let options = {
						filePath: filePath, //文件路径 必填
						userName: itme.name, //必填，用于记录编辑信息
						isEnterReviseMode: true //是否进入修订模式,默认true
					};
					// let i = item
					wpsTool.wpsEditorFile(options, result => {
						const {
							code,
							msg
						} = result;
						if (code == 1) {
							//成功;
							let newPath = result.path; //该路径为绝对路径;
							let relativepath = plus.io.convertAbsoluteFileSystem(newPath); //为平台的相对路径，可以用于上传到服务器;
							this.upLoadDocs(relativepath, itme)
						} else {
							uni.showModal({
								title: "提示",
								content: "抱歉，文档查看失败",
								success: (res) => {
									return
								},
								showCancel: false
							})
						}
					})
				}
			},
			upLoadDocs(relativepath, itme) {
				// console.log(relativepath)
				// console.log(itme)
				let _this = this
				let url = BASE_IP + "/pc/record/update/log/" + itme.recordId + "/" + itme.unitId
				let user = uni.getStorageSync("user")
				uni.uploadFile({
					header: {
						"Authorization": user.token,
					},
					name: "file",
					url: url,
					filePath: relativepath,
					success: (res) => {
						if (res.statusCode == 200) {
							uni.showToast({
								title: "上传成功",
								icon: "success"
							})
							let time = setTimeout((res => {
								_this.getCollapseDatas()
							}), 500)
						}
						if (res.statusCode == 500) {
							uni.showToast({
								title: "上传失败",
								icon: "error"
							})
							return
						}
					},
					fail: (res) => {
						uni.showToast({
							title: "上传失败,请重试",
							icon: "error"
						})
					}
				})
			},
			onSeal(itme) {
				let pralldata = this.pralldata
				// console.log(pralldata)
				let docPath = itme.recordLogUpload
				if (pralldata.unitFireSeal == "" || pralldata.unitFireSeal == undefined) {
					uni.showModal({
						title: "提示",
						content: "单位未上传消防专用章",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								return
							}
						}
					})
					return
				}
				let url = BASE_IP + pralldata.unitFireSeal
				// console.log(url)
				uni.downloadFile({ //下载
					url: url, //图片下载地址
					success: res => {
						if (res.statusCode === 200) {
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: (r) => {
									// console.log(r)
									this.upLoadSeal(r.savedFilePath, docPath, itme)
								}
							})
						}
					}
				});
			},
			/** 盖章函数
			 * @param {Object} filePath 印章图片
			 * @param {Object} docPath  要盖章的文档
			 */
			upLoadSeal(filePath, docPath, itme) {
				let user = uni.getStorageSync("user")
				let url = BASE_IP + "pc/regulatory/update/word"
				uni.uploadFile({
					header: {
						"Authorization": user.token,
					},
					name: "file",
					url: url,
					formData: {
						"unitId": user.unitId,
						"path": docPath
					},
					filePath: filePath,
					success: (res) => {
						// console.log(res)
						if (res.statusCode == 200) {
							uni.showToast({
								title: "盖章成功",
								icon: "success"
							})
							let time = setTimeout((res => {
								this.getCollapseDatas()
							}), 500)
							let time2 = setTimeout((res => {
								this.toViewDoc(itme)
							}), 800)
						}
						if (res.statusCode == 500) {
							uni.showToast({
								title: "上传失败",
								icon: "error"
							})
							return
						}
					},
					fail: (res) => {
						uni.showToast({
							title: "上传失败,请重试",
							icon: "error"
						})
					}
				})
			},
			/** 签字函数
			 * @param {Object} filePath 签字图片
			 * @param {Object} docPath  要签字的文档
			 */
			upSignature(filePath, docPath, item) {
				// console.log(filePath, docPath)
				let user = uni.getStorageSync("user")
				let url = BASE_IP + "pc/regulatory/signature/word"
				uni.uploadFile({
					header: {
						"Authorization": user.token,
					},
					name: "file",
					url: url,
					formData: {
						"unitId": user.unitId,
						"path": docPath
					},
					filePath: filePath,
					success: (res) => {
						if (res.statusCode == 200) {
							uni.showToast({
								title: "签字成功",
								icon: "success"
							})
							let time = setTimeout((res => {
								// this.getUserReminder()
								this.getCollapseDatas()
							}), 500)
							let time2 = setTimeout((res => {
								// this.getUserReminder()
								this.toViewDoc(item)
							}), 800)
						}
						if (res.statusCode == 500) {
							uni.showToast({
								title: "上传失败",
								icon: "error"
							})
							return
						}
					},
					fail: (res) => {
						uni.showToast({
							title: "上传失败,请重试",
							icon: "error"
						})
					}
				})
			},
			setDataOps(res, opsList) {
				const dateTime = moment(res).endOf('day').format('YYYY-MM-DD');
				this.day = dateTime
				this.getCollapseDatas()
			},
			onSelectData(res) {
				// 获取当前日期
				const currentDate = moment();
				// 假设您选择的日期是 "2024-01-01"
				const selectedDate = moment(res.extraInfo.date, 'YYYY-MM-DD');
				// 比较日期
				const isToday = currentDate.isSame(selectedDate, 'day');
				this.isToday = isToday
				const date = res.fulldate;
				const dateTime = date + ' 00:00';
				this.setDataOps(dateTime, this.opsList)
			},
			dataMarking(opsList) {

				const updatedData = opsList.map(item => {
					const recordTime = moment(item.recordTime, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DD');
					return {
						...item,
						recordTime
					};
				});

				console.log("获取原始数据格式化", updatedData)

				let selected = [];
				for (let d in updatedData) {
					let data = {
						date: "",
						info: "已完成"
					};
					data.date = updatedData[d].recordTime;
					selected.push(data);
				}
				const uniqueData = Array.from(new Set(selected.map(JSON.stringify)), JSON.parse);
				console.log(uniqueData);
				this.selected = uniqueData;
				this.dataMarkinSon()
			},
			dataMarkinSon() {

				let user = uni.getStorageSync("user")
				const today = moment().format('YYYY-MM-DD');
				const startDate = moment().subtract(12, 'months').startOf('day'); // 开始日期
				const endDate = moment().subtract(-12, 'months').startOf('day'); // 结束日期
				const dates = [];
				while (startDate.isBefore(endDate)) {
					dates.push(startDate.format('YYYY-MM-DD'));
					startDate.add(this.workRecordTime, 'days');
				}
				let selected = this.selected
				console.log("dataMarkinSon", selected)
				for (let d = 0; d < dates.length; d++) {
					let data = {
						date: "",
						info: ""
					};
					if (!selected.some(item => item.date === dates[d])) {
						data.date = dates[d];
						selected.push(data);
					}
				}
			},
			getUserReminder() {
				let user = uni.getStorageSync("user")
				// console.log(user)
				let url = BASE_IP + "pc/classification/query/" + user.uuid
				let _this = this
				uni.request({
					url: url,
					header: {
						"Authorization": user.token
					},
					success: (res) => {
						let reminder = res.data
						// console.log(reminder)
						for (let i in reminder) {
							if (reminder[i].classifyId == this.regime.classifyId) {
								this.workRecordTime = reminder[i].num
							}
						}
					}
				})
			},
			getPrall() { //获取预设功能对象数据
				let user = uni.getStorageSync("user")
				// console.log(user)
				this.user = user
				let url = BASE_IP + "pc/presetfunction/find/presetFunction/" + user.unitId + "/" + user.uuid
				uni.request({
					header: {
						"Authorization": user.token,
					},
					url: url,
					success: (res) => {
						// console.log(res)
						if (res.statusCode == 200) {
							// this.pralldata = res.data
							uni.setStorageSync("pralldata", this.pralldata)
						} else {
							uni.showToast({
								icon: "error",
								title: "请求失败"
							})
						}
					},
					fail: (res) => {
						// console.log("请求失败：", res)
						uni.showToast({
							icon: "error",
							title: "请求失败"
						})
					}
				})
			},
			init(ops) {
				let user = uni.getStorageSync("user")
				this.getPrall()
				this.getUserReminder()
				let pralldata = uni.getStorageSync("pralldata")
				this.pralldata = pralldata
				// this.getPrall()
				// console.log(pralldata)
				this.user = user
				let d = ops.data
				let regime = JSON.parse(d)
				// console.log("regime", regime)
				this.regime = regime
				uni.setNavigationBarTitle({
					title: regime.classifyName
				})
				const today = moment().format('YYYY-MM-DD HH:mm');
				const startDate = moment().subtract(12, 'months').startOf('day').format('YYYY-MM-DD HH:mm'); // 
				this.startDate = startDate
				let day = moment().format('YYYY-MM-DD');
				// console.log("day：", day)
				this.day = day
				const endDate = moment().subtract('months').startOf('day').format('YYYY-MM-DD HH:mm');
				this.endDate = endDate
				// this.setDataOps(endDate)
				// console.log(regime)
				this.moda.title = regime.classifyName
				this.getCollapseDatas()
			}
		},
		onLoad(ops) {
			setTimeout(() => {
				this.init(ops)
			}, 500)
		},
		onPullDownRefresh() {
			this.getCollapseDatas()
		}
	}
</script>

<style lang="scss">
	.details {
		width: 100%;
		height: 100%;
	}

	button::after {
		border: none;
	}

	.custom-share-btn {
		background: none;
		border: none;
		padding: 0;
		margin: 0;
		line-height: inherit;
		display: inline;
		color: inherit;
		font-size: inherit;
		color: #555;
		display: flex;
		align-items: center;
	}

	.add_user {
		position: fixed;
		right: 10rpx;
		bottom: 20%;
		border-radius: 50%;
		background: #49A0FF;
		color: #fff;
		width: 100rpx;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
	}

	.slot-content {
		width: 100%;
		height: auto;
	}

	.u-page__item {
		margin-top: 50rpx;
		width: 98%;
	}

	.u-page__item-son {
		width: 95%;
		height: 80rpx;
		// background-color: #409EFF;
		display: flex;
		justify-content: space-between;
		margin: auto;
		align-items: center;
	}

	.u-page__item__title__slot-title {
		font-size: 14px;
	}

	.dataOps {
		width: 90%;
		height: auto;
		margin: 10rpx auto;
	}

	.dataOps-num {
		padding-top: 40rpx;
		width: 90%;
		height: auto;
		margin: auto;
		padding-bottom: 10rpx;
		color: #409EFF;
		display: flex;
		justify-content: space-between;
	}

	.fui-text__explain {
		// margin-right: 0;
		position: absolute;
		right: 0px;
		color: #909399;
	}

	.dateCalendar {}

	.fui-item__box {
		width: 100%;
		padding: 26rpx 32rpx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
	}

	.charts-user-list-son {
		width: 95%;
		padding-top: 10rpx;
		padding-bottom: 10rpx;
		margin: 0 auto;
	}
</style>